import dbm

FILE_DB = "file_db"
SHARE_DB = "share_db"


class FileDB:
    def __init__(self):
        pass

    def create_file(self, unique_name: str, file_name: str):
        db = dbm.open(FILE_DB, "c")
        db[unique_name] = file_name.encode('utf-8')
        db.close()

    def get_file(self, unique_name: str):
        db = dbm.open(FILE_DB, "r")
        files = db.keys()
        find_name = bytes(unique_name, 'utf-8')
        if find_name in files:
            # return db.get(unique_name)
            file_name = db[find_name].decode('utf-8')
            db.close()
            return file_name
        else:
            db.close()
            return None

    def get_all_files(self):
        files = dbm.open(FILE_DB, "r")
        codes = dbm.open(SHARE_DB, "r")
        all_files = []
        for key in files.keys():
            file = {
                "unique_name": key.decode('utf-8'),
                "file_name": files[key].decode('utf-8'),
                "code": codes.get(key).decode('utf-8')
            }
            all_files.append(file)
        files.close()
        codes.close()
        return all_files

    def create_share_code(self, unique_name: str, code: str):
        db = dbm.open(SHARE_DB, "c")
        db[unique_name] = code.encode('utf-8')
        db.close()
        return True

    def get_share_code(self, unique_name: str):
        db = dbm.open(SHARE_DB, "r")
        codes = db.keys()
        find_name = bytes(unique_name, 'utf-8')
        if find_name in codes:
            # return db.get(unique_name)
            code = db[find_name].decode('utf-8')
            db.close()
            return code
        else:
            db.close()
            return None

    def delete_file(self, unique_name: str):
        db = dbm.open(FILE_DB, "c")
        if unique_name in db.keys():
            del db[unique_name]
            db.close()
            return True
        else:
            db.close()
            return False

    def update_file(self, unique_name: str, file_name: str):
        db = dbm.open(FILE_DB, "c")
        if unique_name in db.keys():
            db[unique_name] = file_name.encode('utf-8')
            db.close()
            return True
        else:
            db.close()
            return False


file_db = FileDB()
